<template>
  <el-dialog
    title=""
    :visible.sync="isShowPdfImageDialog"
    @close="closePreDialog"
    :class="'pre-file-box'"
  >
    <el-row :class="'pdf-box'" v-if="isShowPdfBox">
      <div class="pdf-content">
        <div
          v-if="loadedRatio > 0 && loadedRatio < 1"
          style="background-color: green; color: white; text-align: center"
          :style="{ width: loadedRatio * 100 + '%' }"
        >
          {{ Math.floor(loadedRatio * 100) }}%
        </div>
        <pdf
          ref="pdf"
          :src="src"
          :page="page"
          @password="password"
          @error="error"
          :rotate="rotate"
          @progress="loadedRatio = $event"
          @numPages="numPages = $event"
        ></pdf>
      </div>
      <div class="operate-box">
        <el-col :span="11" :class="'operate-page-box'">
          <el-button :class="'select-md-btn'" @click="prePage"
            >上一页</el-button
          >
          <el-button :class="'select-md-btn'" @click="nextPage"
            >下一页</el-button
          >
        </el-col>
        <el-col :span="2" :class="'page-count-box'">
          <span class="begin-count">{{ page }}</span>
          <span class="page-sign">/</span>
          <span class="page-sum">{{ numPages }}</span>
        </el-col>
        <el-col :span="11" :class="'revolve-box'"> </el-col>
      </div>
    </el-row>
    <el-row :class="'pup-img-box'" v-if="isShowImgBox">
      <img :src="imgUrl" alt="" />
    </el-row>
    <!-- <iframe :src="this.src"></iframe> -->
  </el-dialog>
</template>
<script>
import { mapGetters, mapState } from "vuex";
import Pdf from "vue-pdf";
import bus from "./../eventBus";
function fetchUploadFileUrl(store, opts) {
  return store.dispatch("FETCH_FILE_URL", opts);
}
function fetchRemoveTempFile(store, opts) {
  return store.dispatch("REMOVE_TEMP_FILE", opts);
}
export default {
  components: {
    Pdf,
  },
  data() {
    return {
      isShowPdfImageDialog: false,
      src: "",
      //src: 'https://cdn.mozilla.net/pdfjs/tracemonkey.pdf',
      loadedRatio: 0,
      page: 1,
      numPages: 0,
      downUrl: "",
      downFileName: "",
      rotate: 0,
      imgUrl: "",
      isShowPdfBox: false, // 预览PDF
      isShowImgBox: false, // 预览图片
      isDown: false, // 是否为下载
      tempSrc: "",
      tempDataType: "", //
    };
  },
  beforeMount() {},
  computed: {
    ...mapGetters(["getUploadFileUrl"]),
    ...mapState(["files"]),
  },
  created() {},
  mounted() {
    bus.$on("show-pdf-img-pup", this.showPup);
  },
  methods: {
    password: function (updatePassword, reason) {
      updatePassword(prompt('password is "test"'));
    },
    error: function (err) {
      console.log("预览错误！");
    },
    prePage() {
      // 上一页
      if (this.page > 1) {
        this.page--;
      } else {
        return;
      }
    },
    nextPage() {
      // 下一页
      if (this.page === this.numPages) {
        return;
      } else {
        this.page++;
      }
    },
    _showMessage(type, msg, fn) {
      this.$message({
        showClose: false,
        message: msg,
        type: type,
        onClose: function () {
          if (fn instanceof Function) {
            fn && fn();
          }
        },
      });
    },
    showPup(data) {
      let tempFiloderPath = FILE_URL + "download/";
      let dataUrl = "";
      dataUrl = data.url;
      let ieJson = window.navigator.userAgent,
        isIe = false;
      this.tempDataType = data.type;
      if (ieJson.indexOf("MSIE 10") !== -1 && data.type === "pdf") {
        isIe = true;
        data.type = "down";
      }

      fetchUploadFileUrl(this.$store, {
        fileUrl: dataUrl,
        isSave: data.isSave,
        flag: data.type,
      })
        .then(() => {
          let tempObj = this.getUploadFileUrl;
          if (tempObj.state === "0000") {
            this.tempSrc = this.files.data;
            let tempFileUrl = "",
              imgType = tempObj.spareResult;
            if (imgType) {
              imgType = imgType === "jpg" ? "jpeg" : "png";
              tempFileUrl = `data:image/${imgType};base64,${this.tempSrc}`;
            } else {
              this._showMessage("图片格式不正确！", "error");
              return;
            }
            tempObj = {};
            if (data.type === "img" || data.preType === "img") {
              this.isShowPdfBox = false;
              this.isShowImgBox = true;
              this.imgUrl = tempFileUrl;
              this.isShowPdfImageDialog = true;
            } else if (data.type === "pdf" || data.preType === "pdf") {
              this.isShowImgBox = false;
              this.isShowPdfBox = true;
              this.src = tempFileUrl;
              this.isShowPdfImageDialog = true;
            } else if (data.type === "down") {
              this.isShowImgBox = false;
              this.isShowPdfBox = false;
              this.downUrl = tempFileUrl;
              this.downFileName = new Date().getTime();
              if (isIe) {
                this._showMessage(
                  "error",
                  "此浏览器版本较低，不支持预览，请点击保存或打开！"
                );
              }
              bus.$emit("down-file", this.downUrl, this.downFileName);
            }
          } else {
            console.log("预览不到！");
          }
        })
        .catch(function (err) {
          console.log("error", err);
        });
    },
    closePreDialog() {
      if (this.tempDataType === "pre-pdf" || this.tempDataType === "pre-img") {
        return;
      }
      fetchRemoveTempFile(this.$store, { name: this.tempSrc }).then(() => {
        let tempObj = this.$store.getters.getRemoveTempFiles;
        if (tempObj.state === "0000") {
          this.src = "";
          this.tempSrc = "";
        } else {
          console.log("删除临时失败！");
        }
      });
      this.page = 1;
    },
  },

  beforeDestroy() {
    bus.$off("show-pdf-img-pup", this.showPup);
    bus.$off("down-file", this.showPup);
  },
};
</script>
<style lang="scss">
@import "./../assets/scss/mixins.scss";
.pre-file-box {
  .el-dialog {
    margin-top: 5vh !important;
    width: 60%;
    .el-dialog__header {
      padding: 0px;
      height: 40px;
    }
  }

  .el-dialog__headerbtn .el-dialog__close {
    z-index: 999;
    position: relative;
  }
  .el-dialog__headerbtn:focus .el-dialog__close,
  .el-dialog__headerbtn:hover .el-dialog__close {
    color: #fa8919;
    border: none;
  }
  .el-dialog__body {
    padding: 0px;
    min-height: 30px;
    padding-top: 10px;
    padding-bottom: 10px;
  }
  .operate-page-box {
    text-align: right;
  }
  .page-count-box {
  }
  .revolve-box {
    text-align: left;
  }
  .operate-page-box,
  .page-count-box,
  .revolve-box {
    height: 45px;
    line-height: 45px;
  }
  .pdf-content {
    width: 95%;
    margin: 0px auto;
    overflow: hidden;
  }
  .annotationLayer {
    width: 100%;
  }
  .pup-img-box {
    width: 100%;
    padding-bottom: 20px;
    padding-left: 20px;
    padding-right: 20px;
    img {
      width: 100%;
      max-width: 100%;
      height: auto;
    }
  }
}

.operate-box {
  height: auto;
  overflow: hidden;
  margin-bottom: 20px;
}
</style>
